package org.mcflier.appuntamento.main;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Properties;
import java.util.logging.Logger;

import org.mcflier.appuntamento.core.Factory;
import org.mcflier.appuntamento.core.exception.ModulesException;
import org.mcflier.appuntamento.core.exception.PropertiesException;
import org.mcflier.appuntamento.core.logger.LoggerManager;
import org.mcflier.appuntamento.core.modules.ModulesManager;
import org.mcflier.appuntamento.core.properties.PropertiesManager;
import org.mcflier.appuntamento.db.DBManager;
import org.mcflier.appuntamento.db.exception.DatabaseConnectionException;
import org.mcflier.appuntamento.db.exception.DatabaseServerException;
import org.mcflier.appuntamento.tasks.TaskManager;


public class PeriodicTasks {

	private static final String FIRST_EXEC_TAG = "first_exec";

	public static void main(String[] args) {
		Factory factory = Factory.getInstance();
		Logger logger = null;
		try {
			ModulesManager modules = (ModulesManager)factory.getModuleInstance(Factory.MODULE_MODULES);
			TaskManager tasks = (TaskManager)factory.getModuleInstance(Factory.MODULE_TASKS);
			DBManager db = (DBManager)factory.getModuleInstance(Factory.MODULE_DB);
			PropertiesManager propertiesManager = (PropertiesManager)factory.getModuleInstance(Factory.MODULE_PROPERTIES);
			Properties properties = propertiesManager.getProperties();
			logger = ((LoggerManager)factory.getModuleInstance(Factory.MODULE_LOGGER)).getLogger(PeriodicTasks.class.getName());

			modules.loadModules();
			db.startDatabase();
			if(Boolean.parseBoolean(properties.getProperty(FIRST_EXEC_TAG, "true"))){
				logger.info("Reseting the database");
				propertiesManager.addProperty(FIRST_EXEC_TAG, "false");
				propertiesManager.storeProperties();
				db.resetDatabase();
			}
			tasks.beginTasks();

			BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
			String word;
			do{
				System.out.print("Type exit for ending the program: ");
				word = reader.readLine();
				System.out.println();
			}
			while(!word.trim().toLowerCase().equals("exit"));

			tasks.stopTasks();
			db.stopDatabase();
			System.out.println("Bye!");

		} catch (ModulesException e) {
			LoggerManager loggerManager = new LoggerManager();
			loggerManager.getLogger(PeriodicTasks.class.getName()).warning("Error loading modules: "+e.getMessage());
			e.printStackTrace();
		} catch (PropertiesException e) {
			logger.warning(e.getMessage());
		} catch (DatabaseServerException e) {
			logger.warning(e.getMessage());
		} catch (DatabaseConnectionException e) {
			logger.warning(e.getMessage());
		} catch (Exception e){
			logger.warning(e.getMessage());
		}
	}
}